package com.bmob.lover.ui.fragment.user

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.qmuiteam.qmui.alpha.QMUIAlphaImageButton
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.getValueNonNull
import com.bmob.lover.R
import com.bmob.lover.app.ext.toJson
import com.bmob.lover.app.util.CacheUtil
import com.bmob.lover.app.util.getCurrentUser
import com.bmob.lover.data.model.enums.BackgroundType
import com.bmob.lover.data.model.bean.Background
import com.bmob.lover.data.model.bean.TheFile
import com.bmob.lover.ui.fragment.base.BaseImageFragment
import com.bmob.lover.viewmodel.AppViewModel
import com.bmob.lover.viewmodel.EventViewModel
import com.bmob.lover.viewmodel.request.UserBgRequestViewModel
import com.bmob.lover.viewmodel.request.LauncherBgSaveViewModel
import com.bmob.lover.viewmodel.request.UserUpdateViewModel
import com.bmob.lover.viewmodel.state.LauncherBgViewModel
import com.theone.common.callback.IImageUrl
import com.theone.mvvm.core.base.fragment.BaseImageSnapFragment
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.core.app.ext.showLoadingPage
import com.theone.mvvm.ext.getAppViewModel
import com.theone.mvvm.ext.qmui.showSuccessTipsDialog

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-05-18 09:41
 * @describe TODO
 * @email 625805189@qq.com
 * @remark
 */
class UserBgFragment private constructor() :
    BaseImageFragment<TheFile, LauncherBgViewModel>() {

    companion object {
        fun newInstance(type: Int): UserBgFragment {
            return UserBgFragment().apply {
                arguments = Bundle().apply {
                    putInt(BundleConstant.TYPE, type)
                }
            }
        }
    }

    private val mType: Int by getValueNonNull(BundleConstant.TYPE)

    private val mUser by lazy {
        getCurrentUser()
    }

    private val mPublishVm: LauncherBgSaveViewModel by viewModels()
    private val mRequestVm: UserBgRequestViewModel by viewModels()
    private val mUserVm: UserUpdateViewModel by viewModels()
    private val mEventVm: EventViewModel by lazy { getAppViewModel<EventViewModel>() }
    private val mAppVm: AppViewModel by lazy { getAppViewModel<AppViewModel>() }

    private var mBackBtn: QMUIAlphaImageButton?= null
    private var mAddBtn: QMUIAlphaImageButton?= null

    private var mBackground: Background? = null
    private var mSelectFile: TheFile? = null
    private var mSelectPosition: Int = 0

    /**
     * 是否为当前用户正在使用的
     */
    private var isUse: Boolean = false

    override fun translucentFull(): Boolean = true

    override fun initView(root: View) {
        super.initView(root)
        getTopBar()?.run {
            mBackBtn = addLeftImageButton(R.drawable.mz_comment_titlebar_ic_close_dark,R.id.qmui_topbar_item_left_back).apply {
                setOnClickListener {
                    finish()
                }
            }
            mAddBtn = addRightImageButton(
                R.drawable.icon_add_dark,
                R.id.topbar_right_view
            ).apply {
                setOnClickListener {
                    startFragment(
                        UserBgAddFragment.newInstance(
                            mType,
                            mBackground
                        )
                    )
                }
            }
        }
        mRequestVm.mBackgroundType = mType
    }

    override fun onFirstLoading() {
        showLoadingPage()
        mRequestVm.run {
            isFirst = true
            requestNewData()
        }
    }

    override fun onRefresh() {
        mRequestVm.run {
            isFresh = true
            requestNewData()
        }
    }

    override fun createObserver() {
        addLoadingObserve(mUserVm, mPublishVm)
        addFailTipsObserve(mPublishVm, mUserVm)
        mRequestVm.run {
            getResponseLiveData().observe(this@UserBgFragment, androidx.lifecycle.Observer {
                if (it.isNotEmpty()) {
                    mBackground = it[0]
                    onFirstLoadSuccess(mBackground!!.getFiles())
                } else {
                    onEmptyData()
                }
            })
            getErrorLiveData().observe(this@UserBgFragment, androidx.lifecycle.Observer {
                onFirstLoadError(it)
            })
        }
        mPublishVm.getObjectSuccessLiveDate().observe(this, androidx.lifecycle.Observer {
            showSuccessTipsDialog("更新成功")
            onAutoRefresh()
        })
        mUserVm.getObjectSuccessLiveDate().observe(this, androidx.lifecycle.Observer {
            showSuccessTipsDialog("更改成功")
            if (mType == BackgroundType.DYNAMIC) {
                mAppVm.setUserInfo(mUser)
            }else{
                CacheUtil.setUser(mUser)
            }
            onScrollChanged(mSelectFile!!, mSelectPosition, getAdapter().data.size)
        })
        mEventVm.getPublishLiveData().observe(this, androidx.lifecycle.Observer {
            if (it == "UserBackground$mType") {
                onAutoRefresh()
            }
        })
    }

    override fun onFirstLoadSuccess(data: List<TheFile>) {
        super.onFirstLoadSuccess(data)
        mBackBtn?.setImageResource(R.drawable.mz_comment_titlebar_ic_close_light)
        mAddBtn?.setImageResource(R.drawable.icon_add_light)
        getRefreshLayout()?.isEnabled = false
        getAdapter().loadMoreModule.loadMoreEnd(true)
        onScrollChanged(data[0], 0, data.size)
    }

    override fun onScrollChanged(item: TheFile, position: Int, total: Int) {
        getTopBar()?.run {
            isUse = if (mType == BackgroundType.DYNAMIC) {
                mUser?.ringBg
            } else {
                mUser?.launchBg
            } == item.path
            setTitle("${position + 1}/$total")
            setSubTitle(if (isUse) "√" else "")
        }
    }

    override fun onPreviewLongClick(media: IImageUrl, position: Int) {
        if (!isUse) {
            mSelectFile = media as TheFile
            mSelectPosition = position
            showBottomActionDialog()
        }
    }

    private fun showBottomActionDialog() {
        QMUIBottomSheet.BottomListSheetBuilder(mActivity).apply {
            setAddCancelBtn(true)
            setGravityCenter(true)
            addItem("设置")
            addItem("删除")
            setOnSheetItemClickListener { dialog, itemView, position, tag ->
                dialog.dismiss()
                if (position == 0) {
                    updateUserLauncherBg()
                } else {
                    deleteFile()
                }
            }
        }.build().show()
    }

    private fun updateUserLauncherBg() {
        mUser?.let {
            if (mType == BackgroundType.LAUNCHER) {
                it.launchBg = mSelectFile?.path
                mUserVm.updateUserLauncherBg(it)
            } else {
                it.ringBg = mSelectFile?.path
                mUserVm.updateUserDynamicBg(it)
            }
        }
    }

    private fun deleteFile() {
        mBackground?.let {
            val list = mutableListOf<TheFile>()
            for (file in it.getFiles()) {
                if (file.path != mSelectFile?.path) {
                    list.add(file)
                }
            }
            it.attachments = list.toJson()
            mPublishVm.update(it)
        }

    }

}